<template>
  <el-row>
    <el-card>
      <el-button-group>
        <el-button
          v-for="(item, index) in $t('collectionManagement.caseManagement.caseManagementType')"
          :key="index"
          :type="chType === item['value'] ? 'primary' : ''"
          @click="changeStatus(item['value'])"
        >
          {{ item['desc'] }}
        </el-button>
      </el-button-group>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.shouldDate')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.days')">
          <el-input-number
            v-model="searchForm.dueDays"
            :controls="false"
            :max="10000000000000"
            :placeholder="$t('collectionManagement.caseManagement.prompt.days')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.stage')">
          <el-select v-model="searchForm.stageId" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.stage')">
            <el-option
              v-for="item in allStage"
              :key="item.id"
              :label="item.phaseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.personnel')">
          <el-cascader
            ref="cascader"
            v-model="searchForm.staffId"
            clearable
            :options="allStaff"
            :props="{ expandTrigger: 'hover' }"
            :placeholder="$t('collectionManagement.caseManagement.prompt.personnel')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.reminderTime')">
          <el-date-picker
            v-model="reminderTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.orderType')">
          <el-select v-model="searchForm.orderType" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.orderType')">
            <el-option
              v-for="item in $t('collectionManagement.caseManagement.orderType')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.orderNo')">
          <el-input v-model="searchForm.orderNo" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.orderNo')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.phoneNumber')">
          <el-input v-model="searchForm.phonenum" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.phoneNumber')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('collectionManagement.caseManagement.searchModel.name')">
          <el-input v-model="searchForm.username" clearable :placeholder="$t('collectionManagement.caseManagement.prompt.name')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-button :disabled="multipleSelection.length === 0" type="primary" @click="allocation">
        {{ $t('collectionManagement.caseManagement.distribution') }}<span v-if="multipleSelection.length > 0">（{{ multipleSelection.length }}）</span>
      </el-button>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        tooltip-effect="dark"
        :stripe="true"
        style="width: 100%;margin-top: 10px"
        @selection-change="handleSelectionChange"
        @sort-change="changeSort"
      >
        <el-table-column
          fixed="left"
          type="selection"
          width="55"
          :selectable="selectable"
        />
        <el-table-column
          fixed="left"
          prop="creditOrderNo"
          :label="tableText['letterReview']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="auth(scope.row)">
              {{ scope.row.creditOrderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          fixed="left"
          prop="orderNo"
          :label="tableText['orderNo']"
          min-width="170"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="toDetail(scope.row)">
              {{ scope.row.orderNo }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="staffName"
          :label="tableText['recruiter']"
          min-width="200"
        />
        <el-table-column
          prop="collectionLogRemark"
          :label="tableText['collectionLog']"
          min-width="150"
        />
        <el-table-column
          prop="collectionLogTime"
          :label="tableText['updateTime']"
          min-width="150"
        />
        <el-table-column
          prop="remindTime"
          :label="tableText['reminderTime']"
          min-width="150"
        />
        <el-table-column
          prop="keep"
          :label="tableText['retain']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ $t('collectionManagement.caseManagement.keep')[scope.row['keep']] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderCreateTime"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="userPhone"
          :label="tableText['userNo']"
          min-width="150"
        />
        <el-table-column
          prop="userName"
          :label="tableText['userName']"
          min-width="200"
        />
        <el-table-column
          prop="orderType"
          :label="tableText['productType']"
          min-width="250"
        >
          <template slot-scope="scope">
            {{ setType(scope.row['orderType']) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="applyMoney"
          :label="tableText['applyCash']"
          min-width="120"
        />
        <el-table-column
          prop="loanDays"
          :label="tableText['limit']"
          min-width="120"
        >
          <template slot-scope="scope">
            <p v-if="scope.row['loanDays'] && scope.row['loanMonths']">
              {{ scope.row['loanDays'] * scope.row['loanMonths'] }} {{ $t('collectionManagement.caseManagement.day') }}
            </p>
          </template>
        </el-table-column>
        <el-table-column
          prop="currentPeriod"
          :label="tableText['period']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row['currentPeriod'] }} / {{ scope.row['totalPeriod'] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepay"
          :label="tableText['repayMoneyShould']"
          min-width="170"
        />
        <el-table-column
          prop="applyMoney"
          :label="tableText['principal']"
          min-width="150"
        />
        <el-table-column
          prop="interestMoney"
          :label="tableText['interest']"
          min-width="120"
        />
        <el-table-column
          prop="serviceCharge"
          :label="tableText['serviceFee']"
          min-width="190"
        />
        <el-table-column
          prop="overDueFine"
          :label="tableText['overdueFee']"
          min-width="150"
        />
        <el-table-column
          prop="planRepaymentDate"
          :label="tableText['RepayTimeShould']"
          min-width="170"
        />
        <el-table-column
          prop="dueDays"
          :label="tableText['dueDay']"
          sortable
          min-width="120"
        >
          <template slot-scope="scope">
            {{ scope.row['dueDays'] }} {{ $t('collectionManagement.caseManagement.day') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="realRepayMoney"
          :label="tableText['realRepayMoney']"
          min-width="120"
        />
        <el-table-column
          prop="realRepaymentDate"
          :label="tableText['repaymentDate']"
          min-width="120"
        />
        <el-table-column
          prop="currentRepay"
          :label="tableText['amountDue']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          prop="orderStatus"
          :label="tableText['orderStatus']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ $t('collectionManagement.caseManagement.stats')[scope.row['orderStatus']] }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="150"
        >
          <template slot-scope="scope">
            <el-row v-if="scope.row['orderStatus'] === 11 || scope.row['orderStatus'] === 5 || scope.row['orderStatus'] === 3 || scope.row['orderStatus'] === 1">
              <el-button v-if="scope.row['keep'] === 2" size="small" @click="retain(scope.row['id'], 1)">{{ $t('collectionManagement.caseManagement.retain') }}</el-button>
              <el-button v-if="scope.row['keep'] === 1" size="small" @click="retain(scope.row['id'], 2)">
                {{ $t('collectionManagement.caseManagement.cancelRetain') }}
                <span style="padding-left: 5px">
                  {{ scope.row['remainDays'] }}{{ $t('collectionManagement.caseManagement.day') }}
                </span>
              </el-button>
            </el-row>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <allocation-dialog
      :show-dialog="allocationDialog"
      :all-staff="allocationStaff"
      :credit-order-ids="creditOrderIds"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getBusinessConfig, getAllOverdueStaff, queryOverdueOrder, getCurrentEmployeeStaffID, setOverdueOrderKeep, exportOverdueOrder } from '@/api/collection'
import { formatDate, ObjToQueryString } from '@/utils/method'
import AllocationDialog from '@/components/collection/allocation-dialog'
export default {
  name: 'CaseManagement',
  components: {
    AllocationDialog
  },
  data() {
    return {
      loading: true,
      chType: 1,
      time: null,
      reminderTime: null,
      allStage: [],
      allStaff: [],
      staffData: [],
      allocationStaff: [],
      tableData: [],
      creditOrderIds: [],
      multipleSelection: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      recallPhone: null,
      recallPhonePassword: null,
      allocationDialog: false
    }
  },
  mounted() {
    this.tableText = this.$t('collectionManagement.caseManagement.tabData')
    this.getAllStage()
    this.getAllStaff()
    this.getStaffInfo()
    this.getData()
  },
  methods: {
    selectable(row) {
      return (row['status'] !== 4 && row['status'] !== 6 && row['status'] !== 9 && row['status'] !== 10 && row['status'] !== 12 && row['status'] !== 13 && row['status'] !== 14)
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        planRepaymentDateStart: null,
        planRepaymentDateEnd: null,
        dueDays: null,
        stageId: null,
        staffId: [],
        remindDateStart: null,
        remindDateEnd: null,
        orderType: '',
        userGrade: null,
        orderNo: null,
        phonenum: null,
        isAscend: null,
        username: null,
        columns: ['due_days'],
        orderBy: [true]
      }
    },
    reset() {
      this.$refs.cascader.$refs.panel.clearCheckedNodes()
      this.searchForm = this.params()
      this.time = null
      this.reminderTime = null
      this.getData()
    },
    changeStatus(type) {
      this.chType = type
      this.getData()
    },
    getAllStage() {
      const data = {
        isPage: false
      }
      getBusinessConfig(data)
        .then(res => {
          if (res.success) {
            this.allStage = res.data.filter(item => {
              return item['state'] === 'ACTIVATE'
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getAllStaff() {
      const data = {
        isPage: false
      }
      getAllOverdueStaff(data)
        .then(res => {
          if (res.success) {
            this.staffData = res.data
            this.allStaff = this.optionData(this.staffData)
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getStaffInfo() {
      getCurrentEmployeeStaffID()
        .then(res => {
          if (res.success) {
            this.recallPhone = res.data ? res.data['recallPhone'] : null
            this.recallPhonePassword = res.data ? res.data['recallPhonePassword'] : null
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getData() {
      this.loading = true
      const data = this.searchData()
      data['orderStatus'] = this.chType
      queryOverdueOrder(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    exportList() {
      exportOverdueOrder(this.searchData())
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        dueDays: this.searchForm.dueDays,
        stageId: this.searchForm.stageId,
        staffId: this.searchForm.staffId.length > 0 ? this.searchForm.staffId[2] : [],
        orderType: this.searchForm.orderType,
        userGrade: this.searchForm.userGrade,
        orderNo: this.searchForm.orderNo,
        phonenum: this.searchForm.phonenum,
        isAscend: this.searchForm.isAscend,
        username: this.searchForm.username,
        columns: this.searchForm.columns,
        orderBy: this.searchForm.orderBy
      }
      if (this.time && this.time.length > 1) {
        data['planRepaymentDateStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['planRepaymentDateEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['planRepaymentDateStart'] = null
        data['planRepaymentDateEnd'] = null
      }
      if (this.reminderTime && this.reminderTime.length > 1) {
        data['remindDateStart'] = formatDate(new Date(this.reminderTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['remindDateEnd'] = formatDate(new Date(this.reminderTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['remindDateStart'] = null
        data['remindDateEnd'] = null
      }
      return data
    },
    test() {
      let value = this.searchForm.dueDays
      if (value.length > 0) {
        value = value.replace(/[^0-9]/g, '')
      }
      this.searchForm.dueDays = value
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    toDetail(item) {
      const paramData = {
        from: 'caseManagement',
        orderNo: item['orderNo'],
        userId: item['userId'],
        creditOrderId: item['creditOrderId'],
        orderStatus: item['orderStatus'],
        orderId: item['orderId'],
        staffID: item['staffID'],
        staffName: item['staffName'],
        recallPhone: this.recallPhone,
        recallPhonePassword: this.recallPhonePassword
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/collectionCenter/collectDetail?${para}`, '_blank')
    },
    auth(item) {
      const paramData = {
        from: 'orderList',
        status: item['orderStatus'],
        userId: item['userId'],
        orderId: item['creditOrderId'],
        orderNo: item['creditOrderNo']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
    },
    setType(data) {
      const name = this.$t('collectionManagement.caseManagement.orderType').filter(v => {
        return v['value'] === data
      })
      return name && name[0] && name[0]['desc'] ? name[0]['desc'] : ''
    },
    allocation() {
      if (this.multipleSelection.length > 0) {
        this.creditOrderIds = []
        this.multipleSelection.forEach(v => {
          this.creditOrderIds.push(v.id)
        })
        this.loading = true
        const arr = this.staffData
        if (arr && arr.length === 0) {
          this.$message.error(this.$t('letterReviewOrder.commissionerNo'))
          return
        }
        this.allocationStaff = this.optionData(arr)
        this.allocationDialog = true
        this.loading = false
      }
    },
    optionData(data) {
      const option = []
      data.forEach(item => {
        if (!option.includes(item['firmName'])) {
          option.push(item['firmName'])
        }
      })
      const optionData = []
      option.forEach((v, i) => {
        const children = []
        const a = data.filter(item => {
          return item['firmName'] === v
        })
        const arr1 = []
        a.forEach(item => {
          if (!arr1.includes(item['groupName'])) {
            arr1.push(item['groupName'])
          }
        })
        arr1.forEach((f, index) => {
          const b = a.filter(item => {
            return item['groupName'] === f
          })
          const grand = []
          b.forEach(grandson => {
            grand.push({
              label: grandson['staffName'],
              value: grandson['id']
            })
          })
          children.push(
            {
              label: f,
              value: `groupName${index}`,
              children: grand
            }
          )
        })
        optionData.push({
          label: v,
          value: i,
          children: children
        })
      })
      return optionData
    },
    retain(id, keepFlag) {
      const data = {
        id,
        keepFlag
      }
      this.loading = true
      setOverdueOrderKeep(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    changeSort(val) {
      this.searchForm.isAscend = val.order === 'ascending'
      this.search()
    },
    changeDialog(param) {
      this.allocationDialog = param
    },
    editSuccess() {
      this.getData()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
.el-divider{
  margin: 10px 0;
}
</style>
